<!--
 * @description 组件
 * @author: 陈陈
 * @date: 2025/05/09
 * @phone: 18560000860
 * @email: 18560000860@qq.com
 * @company: 济南晨霜信息技术有限公司 /
 * @business: 承接前后端项目的开发
-->
<template>
	<view
		class="pure-form-item"
		:class="_classes"
		:style="_styles"
		@tap="_handleClick"
	>
		<view class="pure-form-item__body">
			<view class="pure-form-item__left">
				<slot name="left">
					<slot name="icon">
						<view
							class="pure-form-item__icon"
							v-if="iconName"
						>
							<pure-icon
								:name="iconName"
								v-bind="_iconOpts"
							></pure-icon>
						</view>
					</slot>
					<slot name="label">
						<view
							class="pure-form-item__label"
							v-if="label"
						>
							{{ label }}
						</view>
						<slot name="sublabel">
							<view
								class="pure-form-item__sublabel"
								v-if="sublabel"
								>{{ sublabel }}</view
							>
						</slot>
					</slot>
					<slot name="required">
						<view
							class="pure-form-item__required"
							v-if="_isSetRequired"
						>
							{{ _requiredContent }}
						</view>
					</slot>
				</slot>
			</view>
			<view class="pure-form-item__main">
				<view class="pure-form-item__content">
					<slot></slot>
				</view>
				<view class="pure-form-item__right">
					<slot name="right">
						<slot name="arrow">
							<view
								class="pure-form-item__arrow"
								v-if="_showArrow"
							>
								<pure-icon
									:name="_arrowIconName"
									v-bind="_arrowIconOpts"
								></pure-icon>
							</view>
						</slot>
					</slot>
				</view>
			</view>
		</view>
		<view
			class="pure-form-item__tips"
			v-if="_tips || _alwaysTips"
		>
			<!-- 这个 Left 只是用于占位，用于让提示左侧对齐 -->
			<view class="pure-form-item__left pure-form-item__left--placeholder">
				<slot name="left">
					<slot name="icon">
						<view
							class="pure-form-item__icon"
							v-if="iconName"
						>
							<pure-icon
								:name="iconName"
								v-bind="_iconOpts"
							></pure-icon>
						</view>
					</slot>
					<slot name="label">
						<view
							class="pure-form-item__label"
							v-if="label"
						>
							{{ label }}
						</view>
						<slot name="sublabel">
							<view
								class="pure-form-item__sublabel"
								v-if="sublabel"
								>{{ sublabel }}</view
							>
						</slot>
					</slot>
					<slot name="required">
						<view
							class="pure-form-item__required"
							v-if="_isSetRequired"
						>
							{{ _requiredContent }}
						</view>
					</slot>
				</slot>
			</view>
			<view class="pure-form-item__tips__content">
				{{ _tips }}
			</view>
		</view>
	</view>
</template>

<script>
	import commonComponentOptions from "../../config/options";
	export default {
		options: commonComponentOptions
	};
</script>

<script setup>
	import { ref, computed, inject, watch, provide, onMounted, nextTick, getCurrentInstance } from "vue";
	import props from "./props";
	import {
		isPlainObject,
		isFunction,
		isString,
		isBoolean,
		generateUUID,
		getRect,
		delay
	} from "@/uni_modules/pure-utils";

	// 组件实例
	// const instance = getCurrentInstance();

	// 左侧内容布局信息
	// const _leftUid = ref(generateUUID());
	// const _leftWidth = ref(0);

	// 计算左侧内容宽度
	// onMounted(async () => {
	// 	await nextTick();
	// 	await delay(5000);
	// 	getRect(`.${_leftUid.value}`, instance)
	// 		.then((res) => {
	// 			_leftWidth.value = res?.width || 0;
	// 		})
	// 		.catch((err) => {
	// 			// console.error("获取左侧内容宽度失败", err);
	// 		});
	// });

	// -------------------------------------------------------------------------------- Props
	const _props = defineProps(props);

	// -------------------------------------------------------------------------------- Injects
	const PureFormModel = inject("PureFormModel", {}); // 表单数据
	const PureFormRules = inject("PureFormRules", {}); // 表单最终的验证规则
	const PureFormInvalidFields = inject("PureFormInvalidFields", null); // 未通过验证的字段数据
	const PureFormLabelPosition = inject("PureFormLabelPosition", ""); // Label 位置
	const PureFormRequiredSymbol = inject("PureFormRequiredSymbol", ""); // 必填符号
	const PureFormErrorMode = inject("PureFormErrorMode", ""); // 错误提示模式
	const PureFormIconOpts = inject("PureFormIconOpts", {}); // 图标配置
	const PureFormShowArrow = inject("PureFormShowArrow", false); // 是否显示右侧箭头
	const PureFormArrowIconName = inject("PureFormArrowIconName", ""); // 右侧箭头图标名称
	const PureFormArrowIconOpts = inject("PureFormArrowIconOpts", {}); // 右侧箭头图标配置
	const PureFormUpdatePureFormRules = inject("PureFormUpdatePureFormRules", () => {}); // "更新字段的验证规则" 方法
	const PureFormValidateField = inject("PureFormValidateField", () => {}); // "单字段验证" 方法
	const PureFormContentAlign = inject("PureFormContentAlign", "left"); // 内容对齐方式
	const PureFormAlwaysTips = inject("PureFormAlwaysTips", false); // 提示一直显示

	// -------------------------------------------------------------------------------- Emits
	const _emits = defineEmits(["onClick"]);

	// 最终的 Label 位置
	const _labelPosition = computed(() => _props?.labelPosition || PureFormLabelPosition?.value || "left");

	// 是否显示错误提示
	const _isShowTips = computed(() => !!PureFormInvalidFields.value?.[_props.prop]);

	// 最终的图标配置
	const _iconOpts = computed(() => _props?.iconOpts || PureFormIconOpts?.value || {});

	// 最终是否显示右侧箭头
	const _showArrow = computed(() => {
		if (isBoolean(_props?.showArrow)) return _props?.showArrow;
		return PureFormShowArrow?.value || false;
	});

	// 最终的右侧箭头图标名称
	const _arrowIconName = computed(() => _props?.arrowIconName || PureFormArrowIconName?.value || "");

	// 最终的右侧箭头图标配置
	const _arrowIconOpts = computed(() => _props?.arrowIconOpts || PureFormArrowIconOpts?.value || {});

	// 最终的内容对齐方式
	const _contentAlign = computed(() => _props?.contentAlign || PureFormContentAlign?.value || "left");

	// 是否提示一直显示
	const _alwaysTips = computed(() => _props?.alwaysTips || PureFormAlwaysTips?.value || false);

	// 监听字段的验证规则
	watch(
		() => _props.rule,
		(newVal, oldVal) => {
			// 更新字段的验证规则
			if (isFunction(PureFormUpdatePureFormRules)) {
				PureFormUpdatePureFormRules(_props.prop, newVal);
			}
		},
		{
			deep: true,
			immediate: true
		}
	);

	// -------------------------------------------------------------------------------- Classes
	const _classes = computed(() => {
		const array = [];

		// Label 显示位置
		array.push(`pure-form-item__label-position__${_labelPosition.value}`);

		// 显示错误提示
		if (_isShowTips) array.push("pure-form-item--error");

		// 全边框错误提示
		if (PureFormErrorMode?.value === "border") array.push("pure-form-item--error--border-all");
		// 下边框错误提示
		else if (PureFormErrorMode?.value === "border-bottom") array.push("pure-form-item--error--border-bottom");

		// 禁用
		if (_props.disabled) array.push("pure-form-item--disabled");

		// 只读
		if (_props.readonly) array.push("pure-form-item--readonly");

		// 内容对齐方式
		if (_contentAlign.value) array.push(`pure-form-item--content-align-${_contentAlign.value}`);

		// 隐藏必填符号
		if (_props.hideRequiredSymbol) array.push("pure-form-item--hide-required-symbol");

		// 提示一直存在
		if (_alwaysTips.value) array.push("pure-form-item--always-tips");

		return array;
	});

	// -------------------------------------------------------------------------------- Styles
	const _styles = computed(() => {
		const array = [];

		// 箭头旋转角度
		if (_props.arrowRotate) array.push(`--pure-form-item-arrow-rotate: ${_props.arrowRotate}`);

		// 左侧内容宽度
		// array.push(`--pure-form-item-left-width-real: ${_leftWidth.value}px`);

		return array;
	});

	// 该字段的规则
	const _rule = computed(() => {
		// 全局配置的规则
		if (PureFormRules.value?.[_props?.prop]) {
			// 将规则统一成数组格式
			if (isPlainObject(PureFormRules.value[_props.prop])) return [PureFormRules.value[_props.prop]];
			return PureFormRules.value[_props.prop];
		}

		return null;
	});

	// 是否设置了必填
	const _isSetRequired = computed(() => {
		// 单独设置了
		if (_props?.required) return true;

		// 未设置规则
		if (!_rule.value) return false;

		// 找到设置了 required 的规则
		const requiredRule = _rule.value.find((item) => item.required);

		return !!requiredRule;
	});

	// 必填符号内容
	const _requiredContent = computed(() => {
		// 单独设置了必填符号
		if (_props?.requiredSymbol) return _props.requiredSymbol;

		// 使用全局配置的必填符号
		if (PureFormRequiredSymbol?.value) return PureFormRequiredSymbol.value;

		return "";
	});

	// 错误提示
	const _tips = computed(() => {
		// 验证规则提示
		if (PureFormInvalidFields?.value?.[_props.prop]?.[0]?.message) {
			return PureFormInvalidFields.value[_props.prop][0].message;
		}

		return "";
	});

	// 子元素 - 失去焦点事件
	function onBlur() {
		// 是否失去焦点时验证
		if (_rule?.value) {
			const blurRule = _rule.value.find((item) => {
				let trigger = item?.trigger || "";
				if (isString(trigger)) trigger = [trigger];
				return trigger.findIndex((v) => v === "blur") !== -1;
			});
			if (blurRule && isFunction(PureFormValidateField)) {
				PureFormValidateField(_props?.prop).catch(() => {});
			}
		}
	}

	// 子元素 - 值变化事件
	function onChange() {
		// 是否值变化时验证
		if (_rule?.value) {
			const changeRule = _rule.value.find((item) => {
				let trigger = item?.trigger || "";
				if (isString(trigger)) trigger = [trigger];
				return trigger.findIndex((v) => v === "change") !== -1;
			});
			if (changeRule && isFunction(PureFormValidateField)) {
				PureFormValidateField(_props?.prop).catch(() => {});
			}
		}
	}

	// 点击事件
	function _handleClick() {
		_emits("onClick");
	}

	// -------------------------------------------------------------------------------- Provides
	provide("PureFormItemOnBlur", onBlur);
	provide("PureFormItemOnChange", onChange);
</script>

<style scoped lang="scss">
	@import "./style.scss";
</style>
